package com.yuelao.reptile;

import com.yuelao.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Description
 *
 * @author fengliye
 * @version v1.0
 * @date 22/12/2018 15:00
 * @modify detail
 * 版本       修改人        修改时间      修改内容描述
 * ---------------------------------------------
 * <p>
 * ---------------------------------------------
 */
@Slf4j
public class ReptileBook {
    public static void main(String[] args) throws Exception {
        // html模版
        Document docHtml = Jsoup.parse(getTemplate());
        Element body = docHtml.body();
        // 解析书籍
        for (String book : books()) {
            log.info("book:{}", book);
            String url = "http://localhost:8080/book/" + book;
            print("Fetching %s", url);
            Document doc = Jsoup.connect(url).get();
            Elements links = doc.select("a[href][title]"); //"a[href]" //带有href属性的a元素
            for (Element link : links) {

                String[] paths = link.attr("href").split("/");
                if (paths.length == 3) {
                    body.html(doc.select("article").toString());
                    FileUtil.write(book, "index.html", docHtml.toString());
                    log.info("index.html #### {}", trim(link.text(), 35));
                } else if (paths.length > 3) {
                    Document linkDoc = Jsoup.connect(link.attr("abs:href")).get();
                    body.html(linkDoc.select("article").toString());
                    FileUtil.write(book, paths[paths.length - 1], docHtml.toString());
                    log.info("{} #### {}", paths[paths.length - 1], trim(link.text(), 35));
                }
            }

        }
    }


    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width)
            return s.substring(0, width - 1) + ".";
        else
            return s;
    }


    private static String getTemplate() {
        String html = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>pua</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "</body>\n" +
                "</html>";
        return html;
    }

    private static String[] books() {
        String[] books = {"5-traps", "33-alpha-attraction-rules",
                "attraction", "code-approach-bible", "cold-reading",
                "double-your-dating", "magic-bullets", "pua-bible",
                "pua-demos", "real-world-seduction", "the-art-of-seduction",
                "the-juggler-method", "the-mystery-method"};
        return books;
    }
}
